package org.leetcode.middle.leetcode47;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> temp = new LinkedList<>();

    boolean[] used;

    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);

        used = new boolean[nums.length];
        Arrays.fill(used, false);
        backtracking(nums);
        return res;
    }


    private void backtracking2(int[] nums) {
        if (temp.size() == nums.length) {
            res.add(new ArrayList<>(temp));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i]) {
                continue;
            }

            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }

            used[i] = true;
            temp.add(nums[i]);

            backtracking2(nums);

            used[i] = false;
            temp.remove(temp.size() - 1);
        }
    }

    private void backtracking(int[] nums) {
        if (temp.size() == nums.length) {
            res.add(new ArrayList<>(temp));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
                continue;
            }

            if (used[i] == false) {
                used[i] = true;
                temp.addLast(nums[i]);

                backtracking(nums);

                used[i] = false;
                temp.removeLast();
            }
        }
    }

}
